package com.powernode.controller;

import com.powernode.common.Constants;
import com.powernode.common.Result;
import com.powernode.domain.Zfb;
import com.powernode.service.ZfbService;
import com.powernode.utils.MD5Utils;
import com.powernode.utils.WebMvcUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

/**
 * 内容:用来完成登陆和登出
 * 作者:
 */
@RestController
@RequestMapping("login")
public class LoginController {

    @Resource
    private ZfbService zfbService;
    /**
     * 完成登陆
     */
    @PostMapping("doLogin.do")
    public Result doLogin(String name,String pwd,String captcha){
        //验证验证码
        //从session里面得到正确的验证码
        Object code = WebMvcUtils.getSession().getAttribute(Constants.CAPTCHA_CODE);
        if(code.equals(captcha)){
            //比较用户名和密码
            Zfb zfb=zfbService.login(name, MD5Utils.md5(pwd));
            if(null==zfb){
                return new Result(-1,"用户名或密码不正确");
            }
            //把用户对象放到session
            zfb.setPwd("");
            WebMvcUtils.getSession().setAttribute(Constants.SESSION_USER_KEY,zfb);
            return new Result(200,"登陆成功");
        }else{
            return new Result(-1,"验证码不正确");
        }
    }

    /**
     * 退出登陆
     */
    @PostMapping("logout.do")
    public Result logout(){
        try {
            WebMvcUtils.getSession().invalidate();
            return new Result(200,"退出成功");
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(-1,"退出登陆失败");
        }
    }

}
